#include "login.h"
#include "ui_login.h"
#include "register.h"
#include "chatwindow.h"
#include "buddylist.h"
#include <QObject>
#include <QApplication>
#include <QKeyEvent>


Login::Login(QWidget *parent) :
        QDialog(parent),
        m_ui(new Ui::Login)
{
    m_ui->setupUi(this);
    this->setWindowTitle("MyChat Login");
    connect(m_ui->registerButton, SIGNAL(clicked()), this, SLOT(clickedRegister() ) );
    connect(m_ui->loginButton, SIGNAL(clicked()), this, SLOT(setInfo()));
    connect( ClientHandler::clientHandlerInstance(), SIGNAL(authorizationPassed()), this, SLOT(showBuddyList()));
    connect( ClientHandler::clientHandlerInstance(), SIGNAL(authorizationDenied()), this, SLOT(statusLabelUpdate()));
}

Login::~Login()
{
    delete m_ui;
}

void Login::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}


void Login::setInfo()
{
    ClientHandler::clientHandlerInstance()->setUsername(getUsername());
    ClientHandler::clientHandlerInstance()->setPassword(getPassword());
    ClientHandler::clientHandlerInstance()->setFrom(getUsername());
    Network::networkInstance()->createConnection();
    ClientHandler::clientHandlerInstance()->setClientSocket(&Network::networkInstance()->tcpSocket);
    ClientHandler::clientHandlerInstance()->sendAuthorization();

}


QString Login::getUsername()
{
    return m_ui->username->text();
}

QString Login::getPassword()
{
    return m_ui->password->text();
}

void Login::clickedRegister()
{
    this->close();
    Register* registerWindow_p = new Register(this);
    registerWindow_p->show();
}

void Login::showBuddyList()
{
    this->close();
    BuddyList *buddyListWindow_p = new BuddyList(this);
    buddyListWindow_p->show();
    return;
}


void Login::statusLabelUpdate()
{
    m_ui->statusLabel->show();
    m_ui->statusLabel->setText(tr("<FONT COLOR=red>Wrong username or password entered!</FONT>"));
}

void Login::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return)
    {
        setInfo();
    }
}

